import { changeCount, delSelectCart, getCartList } from '@/api/cart'
import { Toast } from 'vant'

export default { // 1.导出对象
  namespaced: true,
  state: { // 2.定义状态
    cartList: []
  },
  mutations: { // 3.定义方法
    setCartList (state, newList) {
      state.cartList = newList
    },
    toggleCheck (state, goodsId) {
      // 让对应的id的项状态取反
      const goods = state.cartList.find(item => item.goods_id === goodsId)
      goods.isChecked = !goods.isChecked
    },
    toggleAllCheck (state, flag) {
      // 让所有的小选框，同步设置
      state.cartList.forEach(item => {
        item.isChecked = flag
      })
    },
    changeCount (state, { goodsId, goodsNum }) {
      const goods = state.cartList.find(item => item.goods_id === goodsId)
      goods.goods_num = goodsNum
    }
  },
  actions: { // 4.定义异步方法
    async getCartAction (context) {
      const { data } = await getCartList()
      //   后台返回的数据中，不包含复选框，所以需要手动添加，为了实现将来的功能
      // 给每一项，添加一个checked属性， 标记当前商品是否被选中
      data.list.forEach(item => {
        item.isChecked = true
      })
      console.log(data.list)
      context.commit('setCartList', data.list)
    },
    async changeCountAction (context, obj) {
      const { goodsNum, goodsId, goodsSkuId } = obj
      // 先本地修改
      context.commit('changeCount', { goodsId, goodsNum })
      // 再同步到后台
      const res = await changeCount(goodsId, goodsNum, goodsSkuId)
      console.log(res)
    },
    // 删除购物车
    async delCartAction (context) {
      const selCartList = context.getters.selCartList
      const cartIds = selCartList.map(item => item.id)
      const res = await delSelectCart(cartIds)
      console.log(res)
      Toast.success('删除成功')

      // 重新拉取最新的购物车数据
      context.dispatch('getCartAction')
    }
  },
  getters: { // 5.定义计算属性
    cartTotal (state) {
      return state.cartList.reduce((sum, item) => {
        return sum + item.goods_num
      }, 0)
    },
    // 选中的商品项
    selCartList (state) {
      return state.cartList.filter(item => item.isChecked)
    },
    // 选中的商品项的个数
    selCount (state, getters) {
      return getters.selCartList.reduce((pre, item) => {
        return pre + item.goods_num
      }, 0)
    },
    // 选中的总价
    selPrice (state, getters) {
      return getters.selCartList.reduce((pre, item) => {
        return pre + item.goods.goods_price_min * item.goods_num
      }, 0).toFixed(2)
    },
    // 是否全选
    isAllChecked (state, getters) {
      return state.cartList.every(item => item.isChecked)
    }
  }
}
